import fs from 'then-fs'

async function getData(){
    const str= await fs.readFile('./data.json','utf8')
    return JSON.parse(str)
}

// getData().then(res=>console.log(res))

async function addData(obj){
    try {
        const arr = await getData()
        obj.id = arr[arr.length - 1].id + 1
        arr.push(obj)
        fs.writeFile('./data.json', JSON.stringify(arr))
        return '添加成功'
    } catch (e) {
        return '添加失败'
    }
}

// addData({
//     "author": "小阿giao",
//     "bookname": "一给窝里giaogiao",
//     "publisher": "网络乞丐出版设"
// }).then(res=>console.log(res))

async function delData(id){
    try {
        const arr = await getData()
        const newArr = arr.filter(value => id !== value.id)
        fs.writeFile('./data.json', JSON.stringify(newArr))
        return '删除成功'
    } catch (e) {
        return '删除失败'
    }
}

// delData(4).then(res=>console.log(res))

async function updateData(obj){
   try {
       const arr = await getData()
       const index = arr.findIndex(value => obj.id === value.id)
       arr.splice(index, 1, obj)
       fs.writeFile('./data.json', JSON.stringify(arr))
       return '修改成功'
   } catch (e) {
       return '修改失败'
   }
}

updateData({
    "author": "小阿giao",
    "bookname": "一给窝里giaogiao",
    "publisher": "网络乞丐出版社",
    "id": 3
}).then(res=>console.log(res))